<template>
  <div>
    <el-dialog

      title="分配角色"
      :visible="showPermissionDialog"
      width="50%"
      @close="closeDialog"
    >
      <!--      @open="openDialog" -->
      <!-- 复选框 -->

      <el-checkbox-group ref="loading" v-model="roleIds">
        <el-checkbox v-for="item in List" :key="item.id" :label="item.id">
          {{ item.name }}
        </el-checkbox>

      </el-checkbox-group>

      <span slot="footer">
        <el-button @click="closeDialog">Cancel</el-button>
        <el-button type="primary" @click="updatePermission">OK</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>

//  封装一个弹出层
// 在弹窗框弹出时,调用获取所有角色的API,然后渲染到组件上
import { getAllRoleAPI } from '@/api/setting.js'
import { getUserDetailByIdAPI } from '@/api/user'
import { assignRolesAPI } from '@/api/employees.js'
export default {
  name: 'UserContrail',
  props: {
    showPermissionDialog: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      List: [], // 角色列表
      roleIds: [], // 选中的角色列表
      currentID: '' // 当前选中的员工id
    }
  },
  mounted() {
    this.getAllRole()
  },
  methods: {
    // 调用根据id获取员工详细的API
    async getUserDetailById(id) {
      this.currentID = id // 保存id
      const res = await getUserDetailByIdAPI(id)
      this.roleIds = res.roleIds
      console.log(this.roleIds)
    },
    // 调用获取员工角色列表API
    async getAllRole() {
      const data = await getAllRoleAPI(1, 100)
      this.List = data.rows
    },

    // 打开弹窗
    // async  openDialog() {
    // //  调用接口
    //   const data = await getAllRoleAPI(1, 100)

    //   this.List = data.rows
    //   // 从这调用就可以获取到从父组件传过来的id
    //   this.$nextTick(() => {
    //     this.getUserDetailById(this.staffID)
    //   })
    // },

    // 关闭弹窗
    closeDialog() {
      this.$emit('update:showPermissionDialog', false)
      // 关闭时把权限id清空,否则会有显示问题
      this.roleIds = []
    },
    // 点击确认
    async  updatePermission() {
      // 调用给员工分配角色的API

      const res = await assignRolesAPI({ id: this.currentID, roleIds: this.roleIds })
      console.log(res)
      this.$message.success('分配权限成功')
      // 确认时同时把权限id清空,否则会有显示问题
      this.roleIds = []
      this.$emit('update:showPermissionDialog', false)
    }
  }
}

</script>

<style lang="scss" scoped>
 .el-checkbox {
   width: 100px;
 }
</style>
